import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:app/src/http/bean/wroks/contract_bean.dart';
import 'package:app/src/manager/ywx_manager.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';

import '../../../generated/app_strings.dart';
import '../../config/app_data_cache.dart';
import '../../manager/audit_manager.dart';
import '../../ui/route/todo/todo.dart';
import '../model/ywx_model.dart';
import 'package:app/src/manager/ywx_manager.dart' as manager;

var _Order = ReviewType.Order;
var _OrderDJchek = ReviewType.OrderDJchek;
var _OrdersChangeFactory = ReviewType.OrdersChangeFactory;

///服务器菜单列表
class YwxLimit extends BaseBean {
  /// <summary>
  /// 业务项Id
  /// </summary>
  String? YwxId = null;

  /// <summary>
  /// 业务项名称
  /// </summary>
  String? YwxName = null;

  /// <summary>
  /// 业务项分组号
  /// </summary>
  String? Group = null;

  /// <summary>
  /// 业务项是否有权限
  /// </summary>
  String? HasLimit = null;

  bool isHasLimit() {
    String? hasLimit = HasLimit?.toLowerCase()?.trim();
    // if(hasLimit == 'true'){
    // // 提成审核列表	N6016-0	是否具备权限：true
    // // 提成审核列表	N6016-0	是否具备权限：true
    // // 提成审核列表	N6016-0	是否具备权限：true
    // // 提成审核列表	N6016-0	是否具备权限：true
    //   print("$YwxName\t$YwxId\t是否具备权限：$hasLimit");
    // }
    if (hasLimit != null && hasLimit == 'true') {
      return true;
    }
    return false;
  }

  YwxLimit() {
    var json = <String, dynamic>{};
    fromJson(json);
  }

  @override
  fromJson(Map<String, dynamic> json) {
    YwxId = json["YwxId"]?.toString() ?? "";
    YwxName = json["YwxName"]?.toString() ?? "";
    Group = json["Group"]?.toString() ?? "";
    HasLimit = json["HasLimit"]?.toString() ?? "";
  }

  @override
  instance() {
    return YwxLimit();
  }

  @override
  Map<String, dynamic> toJson() {
    var map = <String, dynamic>{};
    map["YwxId"] = YwxId;
    map["YwxName"] = YwxName;
    map["Group"] = Group;
    map["HasLimit"] = HasLimit;
    return map;
  }
}

///功能菜单项
class YwxItem {
  ///功能类型
  String? ReviewType = null;

  /// 业务项Id
  String? YwxId = null;

  /// 业务项名称
  String? YwxName = null;

  ///功能类型2；
  String? ReviewType2 = null;

  /// 业务项名称2;
  String? YwxName2 = null;

  ///菜单图标
  String? ImagePath = null;

  ///提成比例审核：是否为：更改记录
  bool changerecord = false;

  YwxItem(
      {this.ReviewType,
      this.YwxId,
      this.YwxName,
      this.ImagePath,
      this.LimitYwxId});

  ///fixme 业务项Id集合,权限判断; 一个 YwxId 不够用，多加几个。
  List<String>? LimitYwxId = null;

  ///是否具备该菜单权限
  bool isHasLimit() {
    var isHasLimit = YwxIdManager.get(YwxId)?.isHasLimit();
    var hasLimit = isHasLimit ?? true;
    //hasLimit=false;
    if (hasLimit) {
      return true;
    } else {
      if (StringUtils.isNotEmpty(LimitYwxId)) {
        bool isHasLimit2 = false;
        LimitYwxId?.forEach((element) {
          if (!isHasLimit2) {
            var isHasLimit3 = YwxIdManager.get(element)?.isHasLimit();
            //print("$LimitYwxId isHasLimit3:$isHasLimit3");
            if (isHasLimit3 ?? false) {
              isHasLimit2 = true;
            }
          }
        });
        return isHasLimit2;
      }
    }
    return false;
  }

  ///跳转到具体的功能项
  void goWorks(BuildContext context) {
    AppRouteHelper.goWorks(context, this);
  }
}

DateTime? newNoticeDateTime = null; //记录最新通知的消息时间

///站内通知栏消息实体类;待审核列表
///服务器菜单列表
class YwxItemNotice extends ContractCopyInfo {
  //fixme 列表传递给详情页的id;详情页提交的id；审核id;============================必不可少
  String? ReviewTypeId = "";

  //fixme 列表显示名称;如： 合同编号 HT20220708001 ，订单编号等。
  String? ReviewTypeName = "";

  ///fixme 审核类型 =============================================================必不可少
  String? ReviewType = null;

  ///fixme 判断审核类型是否已经审核；true 已审核；false未审核 =====================必不可少
  //bool IsApproval = false;

  bool isApproval() {
    if (IsApproval?.toLowerCase().trim() == "true") {
      return true;
    }
    return false;
  }

  /// 业务项Id
  String? YwxId = null;

  ///业务项名称;fixme (在列表信息里有，详情里没有)；如：合同审核(部门审核)
  String? YwxName = null;

  String? StatusName = ""; //审核状态，如": "待审核", 或：已审核

  /// 项目名称
  String? ProjectName = "";

  /// 客户名称
  String? CustomerName = "";

  /// 业务员姓名(销售经理)
  String? SalesmanName = "";

  /// 跟单员姓名(客服经理)
  String? MerchandiserName = "";

  /// 提交日期; "2022/06/09 22:14:16"
  String? InsertDatetime = "";

  DateTime? _insertDatetime = null;
  Duration? _duration = null;

  //与当前的时间差。
  //isRest 是否重新计算
  Duration? distanceTime({bool isRest = false}) {
    if (_duration != null && !isRest) {
      return _duration;
    }
    if (_insertDatetime == null) {
      if (InsertDatetime != null && InsertDatetime!.trim().length > 0) {
        try {
          var strTime = InsertDatetime!.replaceAll("/", "-");
          // 2022-07-29 9:39:42
          // print(
          //     "===============================================================strTime：${strTime}");
          //_insertDatetime = DateTime.parse(strTime);
          _insertDatetime = DateTimeUtils.stringToDateTime(strTime);
        } catch (e) {
          print(
              "===============================================================_insertDatetime异常：${e}");
        }
      }
    }
    if (_insertDatetime != null) {
      _duration = DateTime.now().difference(_insertDatetime!);
    }
    // print(
    //     "时间0===================================================================_insertDatetime:$_insertDatetime\tInsertDatetime:$InsertDatetime");
    return _duration;
  }

  //是否为最新消息
  bool isNew() {
    if (_insertDatetime == null) {
      distanceTime(isRest: true);
    }
    if (newNoticeDateTime == null) {
      String? insertStr = AppDataCache.getInsertDatetime(); //fixme 获取最新存储待审核消息
      // print("===================================================================获取 insertStr:$insertStr");
      if (StringUtils.isNotEmpty(insertStr)) {
        try {
          var strTime = insertStr!.replaceAll("/", "-");
          newNoticeDateTime = DateTimeUtils.stringToDateTime(strTime);
        } catch (e) {
          print(
              "===============================================================_insertDatetime异常2：${e}");
        }
      }
    }
    // print("时间=====================================================================newNoticeDateTime:$newNoticeDateTime\t_insertDatetime:$_insertDatetime");
    if (newNoticeDateTime != null && _insertDatetime != null) {
      var isAfter = _insertDatetime!.isAfter(newNoticeDateTime!);
      // print(
      //     "==================================================================时间对比：_insertDatetime：$_insertDatetime\tnewNoticeDateTime:$newNoticeDateTime\tisAfter:$isAfter");
      if (isAfter) {
        //_showNewDialog(context);
        return true;
      }
    } else {
      //_showNewDialog(context);
      return true;
    }
    return false;
  }

  ///只显示最新待审核的消息。
  showNewDialog(BuildContext context) {
    // print("周期执行了10");
    if (AuditManager.getAuditManager().getDetailsWithAuto()) {
      //print("正在审核详情页面");
      return; //fixme 当前正在审核详情页面；就不弹出待审核提示框了。
    }
    if (_insertDatetime != null) {
      newNoticeDateTime = _insertDatetime; //fixme 存储最新待审核时间
    }
    //print("===================================================================存储 _insertDatetime:$_insertDatetime\tInsertDatetime:$InsertDatetime");
    if (StringUtils.isNotEmpty(InsertDatetime)) {
      AppDataCache.setInsertDatetime(InsertDatetime); //fixme 存储最新待审核时间
    }
    // print("周期执行了11");
    showYwxCount(context);
    // String title = AppStrings.of(context).ToAudit; //待审核事项
    // var YwxName = getYwxItem(context)?.YwxName;
    // // if (StringUtils.isNotEmpty(YwxName)) {
    // //   title = title + ":$YwxName";
    // // }
    // String okText = AppStrings.of(context).CheckDetails; //查看详情
    // String line1 = "$YwxName:$ReviewTypeName";
    // if (StringUtils.isNotEmpty(YwxName)) {
    //   line1 = "${AppStrings.of(context).TypeOfAudit}:$YwxName"; //审核类型：
    // }
    // String content = "";
    // if (StringUtils.isNotEmpty(CustomerName)) {
    //   String line2 =
    //       AppStrings.of(context).CustomerName + "：$CustomerName"; //客户名称
    //   content = line1 + "\n" + line2;
    // } else {
    //   content = line1;
    // }
    // if (StringUtils.isNotEmpty(PersonName)) {
    //   String value = AppStrings.of(context).PersonName + "：$PersonName"; //申请人
    //   content = content + "\n" + value;
    // }
    // if (StringUtils.isNotEmpty(AddDate)) {
    //   String value = AppStrings.of(context).AddDate5 + "：$AddDate"; //申请日期
    //   content = content + "\n" + value;
    // }
    // showDialogWithAlert(context, title: title, content: content, okText: okText)
    //     ?.then((value) {
    //   if (value ?? false) {
    //     goWorksDetails(context);
    //   }
    // });
  }

  ///显示待审核统计数据
  showYwxCount(BuildContext context) {
    // print("周期执行了12");
    YwxModel.getYwxCount(context, false)?.then((value) {
      // print("周期执行了13");
      String title = AppStrings.of(context).ToAudit2; //待审核统计
      String okText = AppStrings.of(context).ToView; //查看
      String content = value?.getAllNum(context, typeName: true) ?? "";
      if (StringUtils.isNotEmpty(content)) {
        // print("周期执行了14");
        var currentRoute = AppRouteHelper.getCurrentRoute();
        //print("current route: $currentRoute\t${TodoRoute}");
        if (currentRoute == "$TodoRoute") {
          //print("相等");
          okText = AppStrings.of(context).determine; //确定
          showDialogWithAlert(context,
                  title: title, content: content, okText: okText)
              ?.then((value) {
            // if (value ?? false) {
            //   AppRouteHelper.goTodo(context); //跳转到待审核列表；当前就在审核待审核列表，不需要跳转。
            // }
          });
        } else {
          //print("不相等");
          showDialogWithAlert(context,
                  title: title, content: content, okText: okText)
              ?.then((value) {
            if (value ?? false) {
              AppRouteHelper.goTodo(context); //跳转到待审核列表
            }
          });
        }
      }
    });
  }

  ///只显示最新待审核的消息。
  showNewNotification() {
    String title = "你有新的审核事项待处理"; //AppStrings.of(context).ToAudit; //待审核事项
    String line1 = "$YwxName:$ReviewTypeName";
    String content;
    if (StringUtils.isNotEmpty(CustomerName)) {
      String line2 = "客户名称" + "：$CustomerName"; //客户名称
      content = line1 + "\n" + line2;
    } else {
      content = line1;
    }
    // FlutterLocalNotifications(null)
    //     .showNotification(null, title: title, content: content);
    NotificationUtils.show(title: title, body: content);
  }

  //获取审核状态
  String getOrderOrStatusName() {
    //审核状态
    if (isNotEmpty(StatusName)) {
      return StatusName!;
    }
    return "";
  }

  //列表根据审核状态，显示查看，还是审核
  // String getShenhe(BuildContext context) {
  //   //fixme IsApproval 最有效
  //   if (IsApproval ?? false) {
  //     return AppStrings.of(context).ToView; //查看
  //   }
  //   return AppStrings.of(context).audit; //审核
  // }

  @override
  fromJson(Map<String, dynamic> json) {
    super.fromJson(json);
    YwxId = json["YwxId"]?.toString() ?? "";
    //print("=====================================================================YwxId:${YwxId}");
    YwxName = json["YwxName"]?.toString() ?? "";
    //print("=====================================================================YwxName:${YwxName}");
    ReviewType = json["ReviewType"]?.toString() ?? "";
    //print("=====================================================================ReviewType:${ReviewType}");
    //PrintUtils.println("IsApproval:\t${json["IsApproval"]}");
    if (json["IsApproval"].toString().toLowerCase() == 'true') {
      IsApproval = "true";
    } else {
      IsApproval = "false";
    }
    //IsApproval = json["IsApproval"] ?? false;
    ReviewTypeName = json["ReviewTypeName"]?.toString() ?? "";
    // print("=====================================================================ReviewTypeName:${ReviewTypeName}");
    StatusName = json["StatusName"]?.toString() ?? "";
    ProjectName = json["ProjectName"]?.toString() ?? "";
    CustomerName = json["CustomerName"]?.toString() ?? "";
    SalesmanName = json["SalesmanName"]?.toString() ?? "";
    MerchandiserName = json["MerchandiserName"]?.toString() ?? "";
    InsertDatetime = json["InsertDatetime"]?.toString() ?? "";
    ReviewTypeId = json["ReviewTypeId"]?.toString() ?? "";
    PersonName = json["PersonName"]?.toString() ?? "";
    AddDate = json["AddDate"]?.toString() ?? "";
  }

  @override
  instance() {
    return YwxItemNotice();
  }

  @override
  Map<String, dynamic> toJson() {
    //var map = <String, dynamic>{};
    var map = super.toJson();
    map["YwxId"] = YwxId;
    map["YwxName"] = YwxName;
    map["ReviewType"] = ReviewType;
    map["IsApproval"] = IsApproval;
    map["ReviewTypeName"] = ReviewTypeName;
    map["StatusName"] = StatusName;
    map["ProjectName"] = ProjectName;
    map["CustomerName"] = CustomerName;
    map["SalesmanName"] = SalesmanName;
    map["MerchandiserName"] = MerchandiserName;
    map["InsertDatetime"] = InsertDatetime;
    map["ReviewTypeId"] = ReviewTypeId;
    map["PersonName"] = PersonName;
    map["AddDate"] = AddDate;
    return map;
  }

  YwxItem? _item = null;
  bool _b = false;

  ///获取 YwxItem；fixme 不为空说明有该审核功能；为空，表示没有该审核功能。（理解为 该审核App还没有做）
  YwxItem? getYwxItem(BuildContext? context) {
    if (_item == null && !_b) {
      // if (StringUtils.isNotEmpty(YwxId)) {
      //   _item = YwxIdManager.getYwxItem(context,
      //       ReviewType: ReviewType, YwxId: YwxId);
      //   _b = true; //防止重复多次无意义的执行。这个方法执行一遍就够了。
      // }
      //fixme YwxId 可能会为空；主要以ReviewType为主。
      _item = YwxIdManager.getYwxItem(context,
          ReviewType: ReviewType, YwxId: YwxId);
      _b = true; //防止重复多次无意义的执行。这个方法执行一遍就够了。
    }
    return _item;
  }

  ///跳转到消息详情
  Future<Object?>? goWorksDetails(BuildContext? context) {
    if (context == null) {
      return Future.value(null);
    }
    // print("=====================================================================1 ReviewType:$ReviewType\tYwxId:$YwxId");
    var id = ReviewTypeId;
    if (ReviewType == _Order ||
        ReviewType == _OrderDJchek ||
        ReviewType == _OrdersChangeFactory) {
      //fixme 订单审核,冻结解冻审核,工厂更换审核；要传递订单号。
      id = ReviewTypeName;
    }
    YwxItem? item = getYwxItem(context);
    // print(
    //     "=====================================================================2 ReviewType:${item?.ReviewType}\tYwxId:${item?.YwxId}");
    // print(
    //     "ReviewType:${ReviewType}\titem?.ReviewType:\t${item?.ReviewType}\t$item");
    if (ReviewType != item?.ReviewType) {
      _item = null;
      _b = false;
      item = getYwxItem(context);
      // print(
      //     "===================================================================进来了");
    }
    // if(item==null){
    //   item=
    // }
    // "ReviewType": "GetPurOrder",
    // "usable": true,
    // "ReviewTypeName": "",
    // "YwxId": "N8002-7",
    // print(
    //     "=====================================================================3 ReviewType:${item?.ReviewType}\tYwxId:${item?.YwxId}\t$item");

    Auditmaterial? material = null;
    if (item?.ReviewType == manager.ReviewType.GetPurDemandList ||
        item?.ReviewType == manager.ReviewType.GetPurDemandListMT02 ||
        item?.ReviewType == manager.ReviewType.GetPurDemandListMT03) {
      ///fixme 请购单审核特定参数
      material = Auditmaterial();
      material?.IsApproval =
          false; //widget.searchInfo.isApproval();//fixme 待审核列表，默认就是false 未审核的。
      material?.YwxName = YwxName ?? "";
    }
    if (item?.ReviewType == null) {
      AppDialog.showDialogWithInfo(context,
          content: AppStrings.of(context!).Doesnothavepermission); //没有该审核类型的权限
    } else {
      return AppRouteHelper.goWorksDetails2(
          context, item, isApproval(), id, ApprovalState, YwxId, YwxName,
          data: this, material: material);
    }
  }
}
